package com.lsw.jgyf.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lsw.Base.BaseRecyclerAdapter;
import com.lsw.jgyf.R;
import com.lsw.jgyf.adapter.HomeFragment1Adapter;
import com.lsw.jgyf.inject.Constants;
import com.lsw.jgyf.model.BannerModel;
import com.lsw.jgyf.model.HomeFragment1Model;
import com.lsw.jgyf.model.PhoneModel;
import com.lsw.jgyf.ui.activity.PhoneDetailsActivity;
import com.lsw.jgyf.ui.activity.WebviewActivity;
import com.lsw.jgyf.ui.base.fragment.BaseFragment;
import com.lsw.jgyf.util.GlideUtils;
import com.lsw.pullableview.PullToRefreshLayout;
import com.lsw.pullableview.PullableScrollView;
import com.lsw.util.DensityUtil;
import com.lsw.util.DeviceUtil;
import com.lsw.util.InputTools;
import com.lsw.util.LogUtils;
import com.lsw.util.StringUtil;
import com.lsw.util.ToastUtil;
import com.lsw.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by lsw on 2018/7/8.
 */

public class HomeFragment1 extends BaseFragment<HomeFragment1Presenter> implements HomeFragment1Contract.View, PullToRefreshLayout.OnRefreshListener {
    //返回键
    @BindView(R.id.action_bar_left_btn)
    ImageView btnLeft;
    //标题
    @BindView(R.id.action_bar_title)
    TextView tvTitle;
    @BindView(R.id.pullToRefreshLayout)
    PullToRefreshLayout pullToRefreshLayout;
    @BindView(R.id.pullableScrollView)
    PullableScrollView pullableScrollView;
    //轮播图
    @BindView(R.id.mybanner)
    ConvenientBanner mybanner;
    //热销机型
    @BindView(R.id.gridview)
    MyGridView gridview;
    HomeFragment1Adapter homeFragment1Adapter;
    @BindView(R.id.et_seach)
    EditText et_seach;
    private int page = Constants.PAGE_START;
    private String name = "";
    @BindView(R.id.ll_seach)
    LinearLayout ll_seach;


    @Override
    protected int getlayoutId() {
        return R.layout.fragment_home1;
    }

    @Override
    protected void initInjector() {
        mFragmentComponent.inject(this);
    }

    @Override
    protected void initEventAndData() {
        pullToRefreshLayout.setOnRefreshListener(this);
        pullableScrollView.setCanPulldown(true);
        gridview.setFocusable(false);
        homeFragment1Adapter = new HomeFragment1Adapter(mContext);
        gridview.setAdapter(homeFragment1Adapter);
        tvTitle.setText("极果优分");
        btnLeft.setVisibility(View.INVISIBLE);
//        btnLeft.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                // 左边按钮点击，默认结束当前视图
//                hideSoftInput(view);
//                getActivity().finish();
//            }
//        });
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, PhoneDetailsActivity.class);
                intent.putExtra("id", homeFragment1Adapter.getList().get(position).getId() + "");
                startActivity(intent);
            }
        });

        et_seach.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //TODO:你自己的业务逻辑
                    name = v.getText().toString().trim();
                    page = Constants.PAGE_START;
                    mPresenter.getData(page + "", name);
                }
                return false;
            }
        });
        ll_seach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputTools.ShowKeyboard(et_seach);
            }
        });
        mPresenter.getData(page + "", name);
//        mPresenter.getBanner();
    }

    @Override
    protected void lazyLoadData() {

    }

    @Override
    public void setData(List<HomeFragment1Model.PhoneListEntity.DataEntity> list, boolean ispage) {
        pullableScrollView.setCanPullup(ispage);
        if (page == 1) {
            homeFragment1Adapter.setData(list);
        } else {
            homeFragment1Adapter.addData(list);
        }

    }

    @Override
    public void setBanner(List<HomeFragment1Model.BannerListEntity.DataEntity> list) {
        initHeaderBanner(list);
    }

    @Override
    public void RefreshFail() {
        pullToRefreshLayout.Resultfinish(PullToRefreshLayout.FAIL);
    }

    @Override
    public void RefreshSucceed() {
        pullToRefreshLayout.Resultfinish(PullToRefreshLayout.SUCCEED);
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        name = et_seach.getText().toString().trim();
        page = Constants.PAGE_START;
//        mPresenter.getBanner();
        mPresenter.getData(page + "", name);
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        mPresenter.getData(++page + "", name);
    }

    /**
     * 顶部轮播图
     */
    private void initHeaderBanner(final List<HomeFragment1Model.BannerListEntity.DataEntity> banners) {
        mybanner.getLayoutParams().height = DensityUtil.getScreenWidth(getContext()) * 4 / 9;
        mybanner.getLayoutParams().width = DensityUtil.getScreenWidth(getContext());
        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
        mybanner.setPages(() -> new LocalImageHolderView(banners,
                        (view, position) -> {
                            if (!StringUtil.isNullOrEmpty(banners.get(position).getUrl())) {
                                Intent intent = new Intent(mContext, WebviewActivity.class);
                                intent.putExtra("url", banners.get(position).getUrl());
                                intent.putExtra("title", banners.get(position).getTitle());
                                startActivity(intent);
                            }
                        }
                )

                , banners)
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.drawable.banner1, R.drawable.banner2})
                .setCanLoop(true);
        mybanner.startTurning(3000);

    }

    public class LocalImageHolderView implements Holder<HomeFragment1Model.BannerListEntity.DataEntity> {
        private ImageView imageView;
        private BaseRecyclerAdapter.OnItemClickListener mOnItemClickListener;
        List<HomeFragment1Model.BannerListEntity.DataEntity> banners;

        public LocalImageHolderView(List<HomeFragment1Model.BannerListEntity.DataEntity> banners, BaseRecyclerAdapter.OnItemClickListener onItemClickListener) {
            this.banners = banners;
            mOnItemClickListener = onItemClickListener;
        }

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, final int position, final HomeFragment1Model.BannerListEntity.DataEntity data) {
//            Glide.with(context).load(banners.get(position))
//                    .crossFade()
//                    .centerCrop()
//                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
//                    .placeholder(R.mipmap.muti_default_pic)
//                    .into(imageView);
            GlideUtils.loadImageView(mContext, banners.get(position).getImg_url(), imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(v, position);
                    }
//                    List<IBanner> imgs = new ArrayList<>();
//                    for (int i = 0; i < banners.size(); i++) {
//                        PublicImage image = new PublicImage();
//                        image.cover = banners.get(i).getPic();
//                        imgs.add(image);
//                    }
//                    if (imgs.size() > 0) {
//                        PhotoViewActivity.startActivity(fActivity,
//                                position, imgs);
//                    }

                }
            });
        }

    }
}
